<template>
  <div>
    <el-tree
      :data="data"
      show-checkbox
      node-key="menuId"
      class="treeStyle"
      icon-class="ivu-icon-ios-arrow-forward"
      ref="tree"
      :default-expanded-keys="expandedKeys"
      :default-checked-keys="checkedKeys"
      :props="defaultProps"
      @check-change="handleCheckChange"
    ></el-tree>
  </div>
</template>

<script>
import { queryAllMenu, addRoleMenu } from '@api/flowable/userManageAPI'
export default {
  name: 'menuManage',
  props: {
    roleInfo: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      data: [],
      defaultProps: {
        children: 'children',
        label: 'menuName'
      },
      expandedKeys: [],
      checkedKeys: [],
      selectedKeys: [],
      actions: [
        {
          text: this.$t('common.save'),
          theme: 'primary',
          handle: () => {
            this.save()
          },
          loading: false
        },
        {
          text: this.$t('common.close'),
          handle: () => {
            this.$emit('Close')
          }
        }
      ]
    }
  },
  created() {
    this.$emit('SetTitle', this.$t('module.userManage.menuSet'))
    this.$emit('SetPageActions', this.actions)
    queryAllMenu(this.roleInfo).then(({ data }) => {
      this.checkedKeys = data.filter(item => item.selected).map(d => d.menuId)
      this.selectedKeys = this.checkedKeys
      this.expandedKeys = this.checkedKeys
      this.data = this.formatData(data, null)
    })
  },
  methods: {
    //格式化菜单数据
    formatData(list, pid) {
      let data = list.filter(item => item.menuParentId == pid)
      if (data.length) {
        data.map(sItem => {
          sItem.children = this.formatData(list, sItem.menuId)
        })
      }
      return data
    },
    handleCheckChange() {
      this.selectedKeys = this.$refs.tree.getCheckedKeys(true)
    },
    save() {
      const selectedMenuKeys = this.selectedKeys
      if (selectedMenuKeys.length) {
        this.actions[0].loading = true
        let param = {
          id: this.roleInfo.id,
          menuIds: selectedMenuKeys
        }
        addRoleMenu(param).then(res => {
          this.actions[0].loading = false
          this.$Message.success({
            content: this.$t('module.userManage.saveSuccess'),
            duration: 3
          })
          this.$emit('Close')
        })
      } else {
        this.$message.error({
          content: this.$t('module.userManage.selctMenu'),
          duration: 3
        })
      }
    }
  }
}
</script>

<style>
</style>